<?php

class Damages_Methods_Request_GetDiscountData extends Damages_Methods_Request {

  /**
   *
   * @var Damages_Methods_Data_EstimatedBudget_DiscountQuery 
   */
  public $estimatedBudget;

  /**
   *
   * @var int 
   */
  public $brandId;

  public function __construct($params) {
    parent::__construct($params);
    $this->estimatedBudget = new Damages_Methods_Data_EstimatedBudget_DiscountQuery($params->estimatedBudget);
    $this->brandId = (int) $params->brandId;
  }

  public function process() {
    return self::calculateDiscount($this->brandId, $this->estimatedBudget->value, $this->estimatedBudget->deductionValue, $this->estimatedBudget->carValue);
  }

  /**
   * 
   * @param int $brandId
   * @param float $value
   * @param float $deduction
   * @param float $carValue
   * @return Damages_Methods_Response_GetDiscountData
   */
  public static function calculateDiscount($brandId, $value, $deduction, $carValue) {
    //    podstawa = wartosc - kwota odliczenia;
//    upust = upust% * wartosc samochodu;
    $deductionBase = $value - $deduction;
    $dbDiscountQuery = DamagesDictDiscountsQuery::create();
    $dbDiscountQuery->addCond('minVal', DamagesDictDiscountsPeer::COST_MIN, $deductionBase, Criteria::LESS_EQUAL);
    $dbDiscountQuery->addCond('minNull', DamagesDictDiscountsPeer::COST_MIN, null, Criteria::ISNULL);
    $dbDiscountQuery->combine(array('minVal', 'minNull'), Criteria::LOGICAL_OR, 'min');
    $dbDiscountQuery->addCond('maxVal', DamagesDictDiscountsPeer::COST_MAX, $deductionBase, Criteria::GREATER_EQUAL);
    $dbDiscountQuery->addCond('maxNull', DamagesDictDiscountsPeer::COST_MAX, null, Criteria::ISNULL);
    $dbDiscountQuery->combine(array('maxVal', 'maxNull'), Criteria::LOGICAL_OR, 'max');
    $dbDiscountQuery->combine(array('min', 'max'), Criteria::LOGICAL_AND);
    $dbDiscount = $dbDiscountQuery->useDictBrandsQuery()
            ->filterById($brandId)
            ->endUse()
            ->findOne();
    $response = new Damages_Methods_Response_GetDiscountData(true);
    if ($dbDiscount instanceof DamagesDictDiscounts) {
      $discountPercentage = $dbDiscount->getDiscount();
      $discountVal = $carValue * $discountPercentage;
      $data = new Damages_Methods_Data_DiscountData($discountPercentage, $discountVal);
      $response->setData($data);
    }
    return $response;
  }

}